#!/bin/sh
# launches dmenu with query to record
display_size="$(xrandr | awk -F'[ +]' '/primary/{print $4" -i :0.0+"$5","$6}')"
killrecording() {
	recpid="$(cat /tmp/recordingpid)"
	kill -15 "$recpid"
	rm -f /tmp/recordingpid
	sleep 3
	kill -9 "$recpid"
	exit
	}

screencast() {
	ffmpeg -y \
	-f x11grab \
	-framerate 60 \
	-s $display_size \
	-f alsa -i default \
	-r 30 \
 	-c:v libx264rgb -crf 0 -preset ultrafast -c:a flac \
	"$HOME/screencast-$(date '+%y%m%d-%H%M-%S').mkv" &
	echo $! > /tmp/recordingpid
       	}

video() {
	ffmpeg \
	-f x11grab \
	-s $display_size \
 	-c:v libx264 -qp 0 -r 30 \
	"$HOME/video-$(date '+%y%m%d-%H%M-%S').mkv" &
	echo $! > /tmp/recordingpid
	}

webcamhidef() {
	ffmpeg \
	-f v4l2 \
	-i /dev/video0 \
	-video_size 1920x1080 \
	"$HOME/webcam-$(date '+%y%m%d-%H%M-%S').mkv" &
	echo $! > /tmp/recordingpid
	}

webcam() {
	ffmpeg \
	-f v4l2 \
	-i /dev/video0 \
	-video_size 640x480 \
	"$HOME/webcam-$(date '+%y%m%d-%H%M-%S').mkv" &
	echo $! > /tmp/recordingpid
	}


audio() {
	ffmpeg \
	-f alsa -i default \
	-c:a flac \
	"$HOME/audio-$(date '+%y%m%d-%H%M-%S').flac" &
	echo $! > /tmp/recordingpid
	updateicon "🎙️"
	}

askrecording() {
	choice=$(printf "screencast\\nvideo\\naudio\\nwebcam\\nwebcam (hi-def)" | dmenu -i -p "Select recording style:")
	case "$choice" in
		screencast) screencast;;
		audio) audio;;
		video) video;;
		webcam) webcam;;
		"webcam (hi-def)") webcamhidef;;
	esac
	}

asktoend() {
	response=$(printf "No\\nYes" | dmenu -i -p "Recording still active. End recording?") &&
	[ "$response" = "Yes" ] &&  killrecording
	}


case "$1" in
	screencast) screencast;;
	audio) audio;;
	video) video;;
	kill) killrecording;;
	*) [ -f /tmp/recordingpid ] && asktoend && exit || askrecording;;
esac
